package com.beiding.codecreater.render.java.common;

import com.beiding.codecreater.render.java.utils.NameUtils;
import com.beiding.codecreater.utils.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class MyPackage {
    //包名
    private String name;

    //所有可渲染的内容
    private Set<MyClass> myClasses = new HashSet<>();

    //必须给定名称
    public MyPackage(String name) {
        setName(name);
    }

    public void addMyClass(MyClass myClass) {
        if (myClasses.contains(myClass)) {
            return;
        }
        myClasses.add(myClass);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        NameUtils.checkPackageName(name);
        this.name = name;
    }

    //将整个包渲染到文件路径下
    public Map<MyClass, String> render() {
        Map<MyClass, String> map = new HashMap<>();
        for (MyClass aClass : myClasses) {
            String r = aClass.render();
            map.put(aClass, r);
        }
        return map;
    }

    //渲染并创建到相应目录下
    public void renderAndToFile(String path) {

        //构建成标准路径
        File root = new File(new File(path).getAbsolutePath() + File.separator + name.replace(".", File.separator));

        Map<MyClass, String> render = render();
        render.forEach((k, v) -> {
            //开始执行写入操作
            String fn = k.getClassName() + ".java";
            try {
                FileUtils.writeStringToFile(v, new File(root, fn), true);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        });

    }

    public void remove(MyClass myClass) {
        this.myClasses.remove(myClass);
    }
}
